package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.UserAddress;
import com.example.mapper.UserAddressMapper;
import com.example.service.UserAddressService;
import com.example.util.BeanCopyPropertiesUtils;
import com.example.vo.LoginUser;
import com.example.vo.UserAddressVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 12057
* @description 针对表【user_address】的数据库操作Service实现
* @createDate 2024-05-13 19:23:29
*/
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress>
    implements UserAddressService{
    @Override
    public List<UserAddress> getAddressByUserId(Integer userId) {
        return baseMapper.getAddressByUserId(userId);
    }


    @Override
    public List<UserAddressVo> getMemberAddress(Long id) {
        List<UserAddressVo>  list= baseMapper.getByUserId(id);
        return list;
    }


    @Override
    public UserAddressVo getDefaultMemberAddress() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        // 构建查询条件，查询默认的用户地址
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAddress::getUserId, id).eq(UserAddress::getIsDefault, true);

        // 从数据库中查询用户的默认地址
        UserAddress userAddress = baseMapper.selectOne(queryWrapper);

        // 检查是否查询到地址
        if (userAddress == null) {
            return null;
        }
        // 将 UserAddress 实体转换为 UserAddressVo
        UserAddressVo vo = BeanCopyPropertiesUtils.copyBean(userAddress, UserAddressVo.class);

        return vo;


    }
}




